package redisinit

import (
	"context"
	"fmt"
	"shop_srv/shop"
	"strconv"
)

func AddCart(UserId, ShopId, ShopStock int64, ShopTitle, ShopCover, ShopStatus string, ShopPrice float64) error {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_%d", UserId, ShopId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"UserId":     UserId,
		"ShopId":     ShopId,
		"ShopTitle":  ShopTitle,
		"ShopStock":  ShopStock,
		"ShopStatus": ShopStatus,
		"ShopPrice":  ShopPrice,
		"ShopCover":  ShopCover,
	}).Err()
}
func CartList(UserId int64) (cartList []*shop.CartList, err error) {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		lists := Rdb.HGetAll(context.Background(), s).Val()
		shopTitle := lists["ShopTitle"]
		shopStatus := lists["ShopStatus"]
		shopStock, _ := strconv.Atoi(lists["ShopStock"])
		shopCover := lists["ShopCover"]
		shopPrice, _ := strconv.ParseFloat(lists["ShopPrice"], 64)
		userId, _ := strconv.Atoi(lists["UserId"])
		cartList = append(cartList, &shop.CartList{
			ShopTitle:  shopTitle,
			ShopStatus: shopStatus,
			ShopStock:  int64(shopStock),
			ShopCover:  shopCover,
			ShopPrice:  float32(shopPrice),
			UserId:     int64(userId),
		})
	}
	return
}
